package cn.o.app.download;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import cn.o.app.event.Listener;
import cn.o.app.net.NetTask.ConnectNotFoundException;
import cn.o.app.queue.QueueItem;

public class DownloadTask extends QueueItem<IDownloadTask> implements
		IDownloadTask {
	public static final String MASK_EXT = ".0";

	protected String mUrl;

	protected String mSavePath;

	protected DownloadAsyncTask mTask;

	public static boolean isDownloadComplete(String savePath) {
		File file = new File(savePath);
		if (!file.exists()) {
			return false;
		}
		File maskFile = new File(savePath + MASK_EXT);
		return maskFile.exists();
	}

	public void addListener(DownloadTaskListener listener) {
		super.addListener(listener);
	}

	@Override
	public String getUrl() {
		return mUrl;
	}

	@Override
	public void setUrl(String url) {
		if (mStarted || mStoped) {
			return;
		}
		mUrl = url;
	}

	public String getSavePath() {
		return mSavePath;
	}

	public void setSavePath(String savePath) {
		if (mStarted || mStoped) {
			return;
		}
		mSavePath = savePath;
	}

	@Override
	public boolean start() {
		boolean result = super.start();
		if (result) {
			this.mTask = new DownloadAsyncTask();
			this.mTask.execute();
		}
		return result;
	}

	@Override
	public boolean stop() {
		boolean result = super.stop();
		if (result) {
			if (this.mTask != null) {
				this.mTask.cancel(true);
			}
		}
		return result;
	}

	class DownloadAsyncTask extends AsyncTask<String, Integer, Object> {

		protected Object doInBackground(String... paramters) {
			try {
				ConnectivityManager connMgr = (ConnectivityManager) mContext
						.getSystemService(Context.CONNECTIVITY_SERVICE);
				NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
				if (networkInfo == null || !networkInfo.isConnected()) {
					return new ConnectNotFoundException();
				}
				File maskFile = new File(mSavePath + MASK_EXT);
				maskFile.createNewFile();
				HttpURLConnection conn = (HttpURLConnection) new URL(mUrl)
						.openConnection();
				conn.setConnectTimeout(10000);
				conn.setReadTimeout(40000);
				conn.setUseCaches(true);
				conn.setDoOutput(false);
				conn.connect();
				byte[] buffer = new byte[1024];
				int bufferIndex = -1;
				FileOutputStream fileOutputStream = new FileOutputStream(
						mSavePath);
				InputStream in = conn.getInputStream();
				while ((bufferIndex = in.read(buffer)) != -1) {
					fileOutputStream.write(buffer, 0, bufferIndex);
				}
				fileOutputStream.close();
				in.close();
				conn.disconnect();
				maskFile.delete();
				return new Object();
			} catch (Exception e) {
				return e;
			}
		}

		protected void onPostExecute(Object object) {
			List<Listener> listeners = getListeners();
			for (Listener listener : listeners) {
				if (listener instanceof IDownloadTaskListener) {
					IDownloadTaskListener targetListener = (IDownloadTaskListener) listener;
					if (object instanceof Exception) {
						targetListener.onException(DownloadTask.this,
								(Exception) object);
					} else {
						targetListener.onComplete(DownloadTask.this);
					}
				}
			}
			stop();
		}
	}

}
